package org.belkodevelop.report.service;

import org.belkodevelop.report.domen.PatientReport;
import org.belkodevelop.role.RoleConstants;
import org.belkodevelop.user.domain.User;
import org.belkodevelop.user.exception.PermissionException;
import org.belkodevelop.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class ReportService {

    @Autowired
    private UserService userService;


    @Transactional
    public PatientReport getPatientReport(long patientId, User user, Date dateStart, Date dateEnd) {
        boolean allow = false;
        if (isAllowBuildReport(patientId, user)) {
            PatientReport patientReport = new PatientReport();
            patientReport.setUser(userService.getUserById(patientId));
            return patientReport;
        } else {
            throw new PermissionException();
        }
    }

    public boolean isAllowBuildReport(long patientId, User user) {
        if (user == null) {
            return false;
        }
        if (patientId == user.getId()) {
            return true;
        } else if (user.getRoles().contains(RoleConstants.ADMIN_ROLE)) {
            return true;
        } else  if (user.getRoles().contains(RoleConstants.DOCTOR_ROLE)) {
            for (User patient: user.getPatients()) {
                if (patient.getId() == patientId) {
                    return true;
                }
            }
        }
        return false;
    }

}
